package cn.genmer.test.security.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * <p>功能描述：地址处理工具类型</p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: 中通快运</p>
 *
 * @author xw.H
 * @version 0.0.1
 * @date 2020/6/19
 */
public class AddressUtils {

    private final static Logger logger = LoggerFactory.getLogger(AddressUtils.class);
    private static AtomicInteger nextInc = new AtomicInteger(random(2));

    public static final List<String> specialCityNameList = Arrays.asList("东莞市", "中山市", "儋州市", "嘉峪关市", "济源市", "仙桃市", "潜江市",
            "天门市", "神农架林区", "五指山市", "文昌市", "琼海市", "万宁市", "东方市", "定安县", "屯昌县",
            "澄迈县", "临高县", "琼中黎族苗族自治县", "保亭黎族苗族自治县",
            "白沙黎族自治县", "昌江黎族自治县", "乐东黎族自治县", "陵水黎族自治县", "石河子市",
            "阿拉尔市", "图木舒克市", "五家渠市", "北屯市",
            "铁门关市", "双河市", "可克达拉市", "昆玉市", "胡杨河市", "新星市");
    private AddressUtils(){}
        /**
     * 地址清洗
     * @param address
     * @return
     **/
    public static String addressRedress(String address) {

        address = address.replace("{", "(")
                .replace("}", ")")
                .replace("<", "(")
                .replace(">", ")");

        //去除参数中的空格与回车及特殊字符
        address = filterIllegalChar(address);

        //纠正地址中旧行政区名称
//        address = DistrictUtils.redressDistrictName(address);

        //当地址长度大于30个字符，进行地址重复行政区移除
        if(address.length() > 50){
            address = removeRepeatDistrict(address);
        }
        return address;
    }

    /**
     * 移除重复省市区县行政区
     * @Author Xw.H
     * @param originalAddress 原始地址
     * @return
     **/
    private static String removeRepeatDistrict(String originalAddress){
        //是否简称省份匹配
        boolean flag = true ;
        int length = originalAddress.length();
        String subAddress = originalAddress ;
        String repeatAddress = originalAddress.substring(0, (int) (length *0.5));
        //
        for (String completeProvince : ValidateUtils.complete_provinces) {
            if (repeatAddress.contains(completeProvince)) {
                subAddress = originalAddress.substring(repeatAddress.lastIndexOf(completeProvince), length);
                flag = false ;
                break;
            }
        }
        //如果全省名称匹配不上使用简写省名匹配
        if(flag){
            for (String province : ValidateUtils.provinces) {
                if(repeatAddress.contains(province)){
                    subAddress = originalAddress.substring(repeatAddress.lastIndexOf(province), length);
                    break;
                }
            }
        }
        return subAddress ;
    }

    /**
     * @description 地址加密地址
     * @param addressRedress 地址
     * @return 20位加密地址
     * @Author Xw.H
     **/
    public static String getEncryptAddress(String addressRedress)  {
        String addressMd5 = "";
        try {
            addressMd5 = MD5(URLEncoder.encode(addressRedress, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
//            throw new BusinessException(-99,"地址加密错误");
        }
        return addressMd5;
    }

    /***
     * MD5加码 生成20位md5码
     */
    public static String MD5(String address) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            return "";
        }
        char[] charArray = address.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++){
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16){
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().substring(6, 26);
    }

    /**
     * 过滤非法字符
     * @Author Xw.H
     * @param 
     * @return 
     **/
    public static String filterIllegalChar(String str) throws PatternSyntaxException {
        // 清除掉所有特殊字符
        String regEx="[^(a-zA-Z0-9\\u4e00-\\u9fa5()\\-)]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        try {
            //去除地址中&nbsp;不换行空格符
            byte bytes[] = {(byte) 0xC2, (byte) 0xA0};
            String UTFSpace = new String(bytes, StandardCharsets.UTF_8);
            return m.replaceAll("").trim().replace(UTFSpace, "");
        } catch (Exception e) {
            logger.error("去除&nbsp;不换行空格符异常", e);
            return m.replaceAll("").trim();
        }
    }


    /**
     * 生成指定位数的随机整数
     * 如果指定位数不足两位，均返回十以内的整数
     * @param size 位数（需大于零）
     * @return 随机整数
     *
     */
    public static int random(int size) {

        Random random = new Random();
        if(size < 2){
            return random.nextInt(10);
        }
        Double pow = Math.pow(10, size - 1);
        int base = pow.intValue();
        int number = base + random.nextInt(base * 9);

        return number;

    }
}
